<template>
    <div>
        <!-- 搜索表单 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="物料名称" class="bold-label">
                        <el-input v-model="params.materialName" placeholder="请输入分类名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="是否启用" class="bold-label">
                        <el-select clearable v-model="params.status" placeholder="选择是或否">
                            <el-option label="是" value="0" />
                            <el-option label="否" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-button :icon="Search" type="primary" @click="SearchMaterialType">搜索</el-button>
                    <el-button :icon="Refresh" type="primary" plain @click="paramsReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="info" plain :icon="Sort" @click="handleUnfold">展开/折叠</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>
        <!-- 表格部分 -->
        <el-row>
            <el-table :data="tableData" row-key="materialId" :default-expand-all="isUnfold"
                :expand-row-keys="expandedRowKeys">
                <el-table-column prop="materialName" label="分类" align="center" />
                <el-table-column prop="sort" label="排序" align="center" />
                <el-table-column prop="material" label="物料/产品" align="center">
                    <template #default="scope">{{ scope.row.material == 0 ? '物料' : '产品' }}</template>
                </el-table-column>
                <el-table-column prop="status" label="是否启用" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 0 ? 'primary' : 'danger'">
                            {{ scope.row.status === 0 ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" />
                <el-table-column width="253px" label="操作" align="center">
                    <template #default="scope">
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="EditPen"
                            @click="handleupdate(scope.$index, scope.row)">修改</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Plus"
                            @click="handleadd(scope.$index, scope.row)">新增</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Delete"
                            v-show="scope.row.parentId !== null" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!-- 弹窗显示 -->
        <el-dialog v-model="dialogVisible" :title="title" draggable width="40%" @close="handleClose">
            <el-form :model="materialForm">
                <el-row>
                    <el-col>
                        <el-form-item label="父分类" class="bold-label">
                            <el-select v-model="materialForm.parentId" disabled
                                :placeholder="materialForm.materialName">
                                <el-option :label="materialForm.materialName" :value="materialForm.parentId || ''" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="分类名称" class="bold-label">
                            <el-input v-model="material.materialName" placeholder="请输入分类名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="sort-col">
                        <el-form-item label="显示排序" class="bold-label">
                            <el-input-number v-model="material.sort" controls-position="right" min="0">
                                <template #input>
                                    <span v-if="material.sort !== 0">{{ material.sort }}</span>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="物料/产品" class="bold-label">
                            <el-radio-group v-model="material.material">
                                <el-radio value="0">物料</el-radio>
                                <el-radio value="1">产品</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="status-col">
                        <el-form-item label="启用状态" class="bold-label">
                            <el-radio-group v-model="material.status">
                                <el-radio value="0">是</el-radio>
                                <el-radio value="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted, nextTick} from 'vue'
import { Search, Refresh, Sort, Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { findMaterial, insertMaterial,deleteMaterial,updateMaterial } from '@/apis/xms/index'
import {ElMessage } from "element-plus";

// 搜索参数
const params = ref({
    materialName: '',
    status: null
})
const tableData = ref([]) // 表格数据
const isUnfold = ref(true) // 默认是否展开
const expandedRowKeys = ref([]) // 展开行
const dialogVisible = ref(false) // 弹窗显示
const title = ref('') // 弹窗标题
// 部分表单数据
const materialForm = ref({
    materialName: '',
    parentId: undefined,
})
// 传输数据
const material = ref({
    materialName: '',
    parentId: undefined,
    sort: null,
    material: null,
    status: "0",
}) 


// 页面加载完成后执行
onMounted(async () => {
    tableData.value = await findMaterial(params.value)
})

/**
 * 搜索物料分类
 */
const SearchMaterialType = async () => {
    if (params.value.status == undefined) {
        params.value.status = null
    }
    try {
        const data = await findMaterial(params.value);
        tableData.value = []; // 清空数据,重新请求数据
        nextTick(() => {
            tableData.value = data;
        });
    } catch (error) {
        console.error('Failed to search material type:', error);
    }
}
/**
 * 处理 展开/折叠
 */
const handleUnfold = () => {
    if (isUnfold.value) {
        expandedRowKeys.value = []
    } else {
        expandedRowKeys.value = tableData.value
    }
    isUnfold.value = !isUnfold.value
}
/**
 * 修改物料产品分类弹窗显示层
 * @param index 行索引
 * @param row 行数据
 */
const handleupdate = (index, row) => {
    title.value = '修改分类'
    dialogVisible.value = true
    materialForm.value.parentId = row.materialId
    materialForm.value.materialName = row.materialName
    material.value.materialName = row.materialName
    material.value.sort = row.sort
    material.value.material = row.material==0?"0":"1"
    material.value.status = row.status==0?"0":"1"
    material.value.materialId = row.materialId
}
/**
 * 新增物料产品分类弹窗显示层
 * @param index 
 * @param row 
 */
const handleadd = (index, row) => {
    title.value = '添加分类'
    dialogVisible.value = true
    materialForm.value.parentId = row.materialId
    materialForm.value.materialName = row.materialName
    material.value.parentId = row.materialId
}
/**
 * 添加物料产品分类，数据提交
 */
const handleSubmit = async () => {
    if(title.value=='添加分类'){
         await insertMaterial(material.value)
    }else{
        await updateMaterial(material.value)
    }
    dialogVisible.value = false
    ElMessage.success(`${title.value}成功`)
    resetData()
    await SearchMaterialType()
}
/**
 * 删除物料产品分类
 * @param index 行索引
 * @param row 行数据
 */
const handleDelete = async (index, row)=>{
    if(row.children==null){
        console.log(row.materialId)
        await deleteMaterial(row.materialId)
        await SearchMaterialType()
        ElMessage.success("删除成功")
        return
    }
    ElMessage.error("分类下有子类，先删除子类")
}

/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    resetData() 
}
/**
 * 重置数据
 */
function resetData() {
    materialForm.value = {
        materialName: '',
        parentId: undefined,
    }
    material.value = {
        materialName: '',
        parentId: undefined,
        sort: null,
        material: null,
        status: "0",
    }
    title.value = ''
}
/**
 * 重置搜索参数
 */
const paramsReset = ()=>{
    params.value = {
        materialName: '',
        status: null
    }
}
</script>

<style scoped>
/* 样式部分，可以根据需求添加 */

.button-right {
    text-align: right;
}

.btn_m {
    padding: 0;
}

.sort-col,
.status-col {
    display: flex;
    justify-content: end;
}
.bold-label{
    font-weight: bold;
}
</style>